import SearchTop from "../../components/searchTop.vue";
import SearchTitle from "../../components/searchTitle.vue";
import slider from "../../components/sliders.vue";
import getGame from '@/api/getSearch'
import getAwardDetail from '@/api/award/award-add'
import { jsCallNative } from "../../common/callnative"
import axios from 'axios';
import reportEvent from "../../components/report.js"

export default {
    components: {
        SearchTop: SearchTop,
        SearchTitle: SearchTitle,
        slider: slider,
    },

    data() {
        return {
           
            sliderList: [1],
            // 推荐游戏的图片
            goodGame: [],
            goodGameRank: [],
            listGame: [],
            hotGame: [],
             // 轮播图的图片
            banners: [{poster:"https://app.caizhanbao.cn/detault/6.png"},{poster:"https://app.caizhanbao.cn/detault/6.png"},{poster:"https://app.caizhanbao.cn/detault/6.png"},{poster:"https://app.caizhanbao.cn/detault/6.png"}],
            userId: '',
            //YY签名以及时间戳
            signs: '',
            timestamp: '',
            playLatests: '',
            gameCategory1: [],
            gameCategory2: [],
            category1: '',
            category2: '',
            softid: "",
            subCategoryIndex: 0,
            categoryIndex: 0,
            token: "",
            channelInfo: {}, // 频道ID
            isLogin: false,
            //进入游戏接口
            gameurl: "http://pitf.vgs.lenovo.com.cn",
            userName:"",
            iconGame: false,
            lenovoUrl: this.gmConf.domainHttps + "privilege.lenovo.com.cn/v3",
            user: {},
            allData: [], // 储存所有数据
            noSerData: false,
            startTime: +new Date(),
            error:"",
            error1:""
        }
    },
    created(){
       //防止页面后退      
       //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外 
        function banBackSpace(e){ 
        var ev = e || window.event;//获取event对象 
        var obj = ev.target || ev.srcElement;//获取事件源 

        var t = obj.type || obj.getAttribute('type');//获取事件源类型 

        //获取作为判断条件的事件类型 
        var vReadOnly = obj.getAttribute('readonly'); 
        var vEnabled = obj.getAttribute('enabled'); 
        //处理null值情况 
        vReadOnly = (vReadOnly == null) ? false : vReadOnly; 
        vEnabled = (vEnabled == null) ? true : vEnabled; 

        //当敲Backspace键时，事件源类型为密码或单行、多行文本的， 
        //并且readonly属性为true或enabled属性为false的，则退格键失效 
        var flag1=(ev.keyCode == 8 && (t=="password" || t=="text" || t=="textarea") 
        && (vReadOnly==true || vEnabled!=true))?true:false; 

        //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效 
        var flag2=(ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") 
        ?true:false; 

        //判断 
        if(flag2){ 
        return false; 
        } 
        if(flag1){ 
        return false; 
        } 
        } 

        //禁止后退键 作用于Firefox、Opera 
        document.onkeypress=banBackSpace; 
        //禁止后退键 作用于IE、Chrome 
        document.onkeydown=banBackSpace; 
    },
    
    mounted() {
        this.getUserInfo()
        this.getGameLists()
        this.getGameTitle()
        this.sliderInit()
        if(typeof this.$route.query.errorMessage != "undefined" && this.$route.query.errorMessage!=""){
            this.$toast.center("错误")
        };
    },
    beforeDestroy(){
        reportEvent.pageOut(this.userId,this.startTime,"101")
    },

    methods: {

         getUrlParam(par) {
            //获取当前URL
            var local_url = document.location.href;
            //获取要取得的get参数位置
            var get = local_url.indexOf(par +"=");
            if(get == -1){
                return false;
            }
            //截取字符串
            var get_par = local_url.slice(par.length + get + 1);
            //判断截取后的字符串是否还有其他get参数
            var nextPar = get_par.indexOf("&");
            if(nextPar != -1){
                get_par = get_par.slice(0, nextPar);
            }
            return get_par;
        },
              //获取用户登录信息

        getUserInfo() { // 通过token来获取用户的基本信息
            this.token=this.getUrlParam("token")
            console.log(this.token)
            if(this.token){
                this.isLogin=true
                 var ts = this
                let url = "/token/user/getUserInfo?time="+new Date().getTime()// 防止ie请求接口缓存
                this.jqajax(url,{type:"POST",dataType:"json",data:{token:ts.token}},function(res){
                    console.log(res)
                        ts.user=res.data
                        ts.userName=res.data.nickname
                        window.sessionStorage.setItem("userName", ts.userName);
                        ts.userId = res.data.lenovoId
                        ts.getSign(res.data.lenovoId)

                        window.sessionStorage.setItem("id",ts.userId)
                        reportEvent.pageIn(ts.userId,"101")
                        
                     
                })
            }else{
                this.isLogin=false
            }

             
        },

        mustLogin: function() { // 点击开始登陆
                  window.external.LoginLenovoID();
                  reportEvent.pageLoginIn(this.userId)

        },
        loginOut: function() {
            window.external.LogoutLenovoID();
            this.isLogin = false;
            reportEvent.pageLoginOut(this.userId)
        },

        showStartGame: function(index, ev) { // 服务器轮播图显示进入游戏
            $(".active .allDataSub li .three")[index].style.display = "none"
            $(".active .allDataSub li .startGame")[index].style.display = "block"
        },
        hideStartGame: function() {
            $(".active .allDataSub li .three").show()
            $(".active .allDataSub li .startGame").hide()
        },
        sliderInit: function() { // 轮播图初始化
            $('.twoCarousel').carousel({
                interval: 5000,
            })
        },
        
        getGameLists() { // 得到banner和服务器列表轮播图的数据
            // 接口地址在serviceUrl里
            getAwardDetail.getAwardDetail(104).then((res) => {
                $(window).scrollTop(0);
                console.log(res.data)
                // 轮播图
                this.banners = res.data.channels[0].modules[1].elements;
                this.banners.page = res.data.channels[0].channelName;
                this.banners.pageId = res.data.channels[0].id;
                // 精品游戏
                this.goodGame =res.data.channels[0].modules[2].elements.slice(0, 4)
               
                this.goodGame =  this.handleData(this.goodGame)

                console.log( this.goodGame)
            

                // 热门游戏
                this.hotGame = res.data.channels[0].modules[4].elements.slice(0, 3);
                //  页游精品游戏开服表
                this.goodGameRank = res.data.channels[0].modules[3].elements;
                console.log()

                //处理goodGameRankList
                
                  if(this.banners.length<=1){
                        $(".banner-carousel").hide()
                    }
                
                if (JSON.stringify(this.goodGameRank) === "[]") {
                   
                    this.noSerData = true
                } else {
                    this.noSerData = false
                    var goodGameRankList = Math.ceil(this.goodGameRank.length / 10)

                     if(goodGameRankList<=1){
                        $(".serviceData").hide()
                    }
                   this.sliderList=[];
                    for (var i = 0; i < goodGameRankList; i++) {

                        (this.sliderList).push(this.goodGameRank.slice(i*10,(i+1)*10))
                    }
                    
                }

            })
        },
        // 获取游戏列表
        async getGameTitle() {
            getGame.getMore().then((res) => {
                console.log(res)
                this.gameCategory1 = res.data.first
                this.gameCategory2 = res.data.second.slice(0,5);
                this.category1 = this.gameCategory1[2].category1
                this.category2 = this.gameCategory2[0].category1
                this.getGame();
            });
        },

        // 点击游戏列表分类
        selectIndex(index, item, ev) {
            let value = ev.target.text
            console.log(value)
            $(".allGameTitle a").removeClass("active")
            $(event.target).addClass("active")
            let arr = []

            if (value == "全部") {
                arr = this.allData
            } else {
                for (var i in this.allData) {
                    if (this.allData[i].category2 == value) {
                        arr.push(this.allData[i])
                    }
                }
            }
            if (JSON.stringify(arr) === '[]') {
                this.iconGame = true
            } else {
                this.iconGame = false
                this.listGame = arr.slice(0, 12);
                this.listGame=this.handleData(this.listGame);


            }

            reportEvent.pageSelect(this.userId)
        },
        handleData(data) {
            // 遍历把235*132的图片加到游戏list里
            console.log(data)
            for (let j = 0; j < data.length; j++) {
                if (!data[j].captureFiles) {
                    data[j].bgUrl = ''
                } else {
                    for (let i = 0; i < data[j].captureFiles.length; i++) {
                        if (data[j].captureFiles[i].size == '270*210') {
                            data[j].bgUrl = data[j].captureFiles[i].url
                        }
                        if (data[j].captureFiles[i].size == '270*600') {
                            data[j].serviceImg = data[j].captureFiles[i].url

                        }

                    }
                    console.log()
                }
            }
            return data
        },

        async getGame() {
            let that=this
          let url = '/search/searchGame?relativeId=48&category1=0&category2=0&page=1';
          axios.get(url).then(function(res){
              if (JSON.stringify(res.data.datas) === '[]') {
                    that.iconGame = true
                    console.log(that.iconGame)
                } else {
                    that.iconGame = false
                    that.allData = res.data.datas
                    that.listGame = res.data.datas.slice(0, 12)
                   that.listGame=that.handleData(that.listGame)
                   console.log(that.listGame)
                }
          })
        },

        goDetails(Id) { // 选择服务器
            if(!this.token){// 验证token
                 window.external.LoginLenovoID();  //登录
                return false;
            }
            let that =this
            this.$router.push({ path: "../service", query: { gameId:Id,token:that.token} })

            reportEvent.pageMoreGame(this.userId)
        },
        /*//获取YYgame
        getGameYY(gameId) {
            var ts = this
            console.log(gameId)
            var _url = "/back/game/get/game/soft/data?softName=yy&gameId=" + gameId;

            var ts = this;

            ts.jqajax(_url, { type: "get", dataType: "json" }, function(res) {
                console.log(res)
                ts.softBrowser = res.data.softkernel;
                ts.softid = res.data.softId; //game值
                ts.gameStart();
            });
        },*/

        //获取YYgame
        getGameYY(cpId,softId,gameName) { // gameId  cpId  softId  游戏名称
                        
            this.gameStart(cpId,softId,gameName);
            
        },
        //1527212938172  1527213846854

        //获取yy签名以及当前时间戳
        getSign(userId) {
            var _url = "/back/game/api/user/md5UserId?&userId="+ userId+"&time="+new Date().getTime()// 防止ie请求接口缓存;
            var ts = this;
            ts.jqajax(_url, { type: "get", dataType: "json" }, function(res) {
                console.log(res)
                ts.signs = res.data.out;
                ts.timestamp = res.data.timestamp;
                ts.error=res.data
                //获得以前玩的游戏
                ts.playAllLatest(res.data.out, res.data.timestamp, ts.userId);
            });
        },




        //获取用户最近在玩的
        playAllLatest(sign, timestamp, userId) { // 最近在玩的所有游戏

            var ts = this;
            // &serverType=GENERAL
            var url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/recently.do?jsonp&" + "&sign=" + sign + "&timestamp=" + timestamp + "&userId=" + userId +"&time="+new Date().getTime();   // 此处加个时间戳，为了防止IE浏览器缓存问题，而不会重新请求数据，而是从缓存里面获取
                  

            this.jqajax(url,{ type: "get", dataType: "jsonp"}, function(res){

                console.log(res)
                if(res.status==200){
                    $(".service-specific-container div").eq(0).remove();
                    if (JSON.stringify(res.data) ==='[]') {

                        ts.playLatests=[]   
                    
                    } else{
                        ts.playLatests = res.data.slice(0, 4);
                    }

                    console.log(ts.playLatests)

                }else{
                    
                }

               
            })
        },

        //开始游戏
        gameStart(cpId,softId,gameName) {
             var url = `${this.gameurl}/gameRedirect/loginGame?cp=${cpId}_GAME&game=${softId}&gameName=${gameName}&token=${this.token}`

            //var url =  ts.gameurl +"/gameRedirect/loginGame"

                window.open(url)
                reportEvent.pageStartGame(this.userId)

        },
       myStartGame: function(game, server) { // 我之前玩过的游戏快速进入游戏
            
            let url ="https://passport.4366.com/channel/lenovo/gamecenter/login.do?token=" + this.token + "&game=" + game + "&server=" + server + "&ref=LXDT/ZHLX&failUrl=" + encodeURIComponent(window.location.href);
            //let url =this.gameurl+"/gameRedirect/loginGame?"
            //https://pitf.vgs.lenovo.com.cn/gameRedirect/loginGame?cp=YY_GAME&game=DMZT&gameName=传奇世界&serviceName=s16&serviceId=s16

            window.open(url)
            reportEvent.pageStartGame(this.userId)
        },

        //客户端弹窗
        popVideo(_url) {
            var ts = this;
            if (!_url || !ts.isLenovo()) return;
            if (!ts.isIe()) {
                callHostFunction.callBackVideo(_url, ts.softBrowser);
            } else {
                window.external.callBackVideo(_url, ts.softBrowser);
            }

        },

        openWin(url) {
            $('body').append($('<a href="' + url + '" target="_blank" id="openWin"></a>'))
            document.getElementById("openWin").click(); //点击事件  
            $('#openWin').remove();
        },
        moreGame() {
            let that =this
            if(!this.token){// 验证token
                 window.external.LoginLenovoID();  //登录
                return false;
            }

            this.$router.push({ path: "../allGame",query:{token:that.token,Id:that.userId}})

            reportEvent.pageMoreGame(this.userId)
        }


    }

}